package cn.joybreeze.controller;


import cn.joybreeze.common.result.R;
import cn.joybreeze.common.vo.QuestionQueryVO;
import cn.joybreeze.model.QuestionDO;
import cn.joybreeze.service.QuestionService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author kjwaa
 * @since 2021-09-15
 */
@RestController
@RequestMapping("/question-do")
public class QuestionController {

    @Autowired
    QuestionService questionService;

    /**
     * 增加问题记录
     * @param questionQueryVO
     * @return
     */
    @PostMapping("/add")
    public R addQuestion(@RequestBody QuestionQueryVO questionQueryVO){
        QuestionDO questionDO = new QuestionDO();
        BeanUtils.copyProperties(questionQueryVO, questionDO);
        boolean isSuccess = questionService.saveOrUpdate(questionDO);
        if(isSuccess) return R.ok(questionDO);
        return R.error();
    }

    /**
     * 根据id删除问题记录
     * @param id
     * @return
     */
    @DeleteMapping("/delete/{id}")
    public R deleteQuestion(@PathVariable int id){
        boolean isSuccess = questionService.removeById(id);
        if(isSuccess) return R.ok();
        return R.error();
    }

    /**
     * 根据问卷id删除问题
     * @param questionnaireId
     * @return
     */
    @DeleteMapping("/deleteByQuestionnaireId/{questionnaireId}")
    public R deleteQuestionByQuestionnaireId(@PathVariable int questionnaireId){
        QueryWrapper<QuestionDO> queryWrapper = new QueryWrapper<>();
        // 这里要和数据库表字段名一样
        queryWrapper.eq("questionnaire_id", questionnaireId);
        boolean isSuccess = questionService.remove(queryWrapper);
        if(isSuccess) return R.ok();
        return R.error();
    }

    /**
     * 根据问卷id查询问题列表
     * @param questionnaireId
     * @return
     */
    @GetMapping("/list/{questionnaireId}")
    public R getListByQuestionnaireId(@PathVariable int questionnaireId){
        QueryWrapper<QuestionDO> queryWrapper = new QueryWrapper<>();
        // 这里写的是数据库列名？
        queryWrapper.eq("questionnaire_id", questionnaireId);
        List<QuestionDO> list = questionService.list(queryWrapper);
        return R.ok(list);
    }


}
